<template>
  <div class="h-screen flex bg-gray-100">
    <!-- 侧边栏 -->
    <div :class="[
      'bg-gray-800 text-white transition-all duration-300 flex flex-col',
      isCollapse ? 'w-16' : 'w-64'
    ]">
      <!-- Logo -->
      <div class="h-16 flex items-center justify-center border-b border-gray-700">
        <img v-if="!isCollapse" src="/favicon.ico" alt="Logo" class="w-8 h-8 mr-2">
        <span v-if="!isCollapse" class="text-lg font-bold">LMS</span>
        <img v-else src="/favicon.ico" alt="Logo" class="w-8 h-8">
      </div>
      
      <!-- 导航菜单 -->
      <nav class="flex-1 py-4">
        <ul class="space-y-1">
          <!-- 仪表盘 -->
          <li>
            <router-link
              to="/"
              :class="[
                'flex items-center px-4 py-2 text-sm font-medium rounded-md mx-2 transition-colors',
                activeMenu === '/' 
                  ? 'bg-primary-600 text-white' 
                  : 'text-gray-300 hover:bg-gray-700 hover:text-white'
              ]"
            >
              <HomeIcon class="w-5 h-5 mr-3" />
              <span v-if="!isCollapse">仪表盘</span>
            </router-link>
          </li>
          
          <!-- 设备管理 -->
          <li v-if="hasAnyRole(['ADMIN', 'LEADER', 'LAB_MANAGER'])">
            <div class="relative">
              <button
                @click="toggleSubMenu('equipment')"
                :class="[
                  'w-full flex items-center justify-between px-4 py-2 text-sm font-medium rounded-md mx-2 transition-colors',
                  'text-gray-300 hover:bg-gray-700 hover:text-white'
                ]"
              >
                <div class="flex items-center">
                  <ComputerDesktopIcon class="w-5 h-5 mr-3" />
                  <span v-if="!isCollapse">设备管理</span>
                </div>
                <ChevronDownIcon 
                  v-if="!isCollapse"
                  :class="[
                    'w-4 h-4 transition-transform',
                    openSubMenus.equipment ? 'rotate-180' : ''
                  ]"
                />
              </button>
              
              <!-- 子菜单 -->
              <div v-if="!isCollapse && openSubMenus.equipment" class="ml-4 mt-1 space-y-1">
                <router-link
                  to="/equipment"
                  :class="[
                    'block px-4 py-2 text-sm rounded-md transition-colors',
                    activeMenu === '/equipment'
                      ? 'bg-primary-600 text-white'
                      : 'text-gray-300 hover:bg-gray-700 hover:text-white'
                  ]"
                >
                  设备列表
                </router-link>
                <router-link
                  to="/equipment-application"
                  :class="[
                    'block px-4 py-2 text-sm rounded-md transition-colors',
                    activeMenu === '/equipment-application'
                      ? 'bg-primary-600 text-white'
                      : 'text-gray-300 hover:bg-gray-700 hover:text-white'
                  ]"
                >
                  设备申请
                </router-link>
                <router-link
                  to="/equipment-borrow"
                  :class="[
                    'block px-4 py-2 text-sm rounded-md transition-colors',
                    activeMenu === '/equipment-borrow'
                      ? 'bg-primary-600 text-white'
                      : 'text-gray-300 hover:bg-gray-700 hover:text-white'
                  ]"
                >
                  借还管理
                </router-link>
              </div>
            </div>
          </li>
          
          <!-- 设备统计 -->
          <li v-if="hasAnyRole(['ADMIN', 'LEADER'])">
            <div class="relative">
              <button
                @click="toggleSubMenu('statistics')"
                :class="[
                  'w-full flex items-center justify-between px-4 py-2 text-sm font-medium rounded-md mx-2 transition-colors',
                  'text-gray-300 hover:bg-gray-700 hover:text-white'
                ]"
              >
                <div class="flex items-center">
                  <ChartBarIcon class="w-5 h-5 mr-3" />
                  <span v-if="!isCollapse">设备统计</span>
                </div>
                <ChevronDownIcon 
                  v-if="!isCollapse"
                  :class="[
                    'w-4 h-4 transition-transform',
                    openSubMenus.statistics ? 'rotate-180' : ''
                  ]"
                />
              </button>
              
              <div v-if="!isCollapse && openSubMenus.statistics" class="ml-4 mt-1 space-y-1">
                <router-link
                  to="/equipment-statistics"
                  :class="[
                    'block px-4 py-2 text-sm rounded-md transition-colors',
                    activeMenu === '/equipment-statistics'
                      ? 'bg-primary-600 text-white'
                      : 'text-gray-300 hover:bg-gray-700 hover:text-white'
                  ]"
                >
                  使用统计
                </router-link>
                <router-link
                  to="/equipment-repair"
                  :class="[
                    'block px-4 py-2 text-sm rounded-md transition-colors',
                    activeMenu === '/equipment-repair'
                      ? 'bg-primary-600 text-white'
                      : 'text-gray-300 hover:bg-gray-700 hover:text-white'
                  ]"
                >
                  维修记录
                </router-link>
                <router-link
                  to="/equipment-scrap"
                  :class="[
                    'block px-4 py-2 text-sm rounded-md transition-colors',
                    activeMenu === '/equipment-scrap'
                      ? 'bg-primary-600 text-white'
                      : 'text-gray-300 hover:bg-gray-700 hover:text-white'
                  ]"
                >
                  报废记录
                </router-link>
              </div>
            </div>
          </li>
          
          <!-- 低值易耗品 -->
          <li v-if="hasAnyRole(['ADMIN', 'LEADER', 'LAB_MANAGER'])">
            <div class="relative">
              <button
                @click="toggleSubMenu('consumable')"
                :class="[
                  'w-full flex items-center justify-between px-4 py-2 text-sm font-medium rounded-md mx-2 transition-colors',
                  'text-gray-300 hover:bg-gray-700 hover:text-white'
                ]"
              >
                <div class="flex items-center">
                  <ArchiveBoxIcon class="w-5 h-5 mr-3" />
                  <span v-if="!isCollapse">易耗品管理</span>
                </div>
                <ChevronDownIcon 
                  v-if="!isCollapse"
                  :class="[
                    'w-4 h-4 transition-transform',
                    openSubMenus.consumable ? 'rotate-180' : ''
                  ]"
                />
              </button>
              
              <div v-if="!isCollapse && openSubMenus.consumable" class="ml-4 mt-1 space-y-1">
                <router-link
                  to="/consumable-plan"
                  :class="[
                    'block px-4 py-2 text-sm rounded-md transition-colors',
                    activeMenu === '/consumable-plan'
                      ? 'bg-primary-600 text-white'
                      : 'text-gray-300 hover:bg-gray-700 hover:text-white'
                  ]"
                >
                  易耗品计划
                </router-link>
                <router-link
                  to="/consumable-receive"
                  :class="[
                    'block px-4 py-2 text-sm rounded-md transition-colors',
                    activeMenu === '/consumable-receive'
                      ? 'bg-primary-600 text-white'
                      : 'text-gray-300 hover:bg-gray-700 hover:text-white'
                  ]"
                >
                  领用记录
                </router-link>
                <router-link
                  v-if="hasAnyRole(['ADMIN', 'LEADER'])"
                  to="/consumable-query"
                  :class="[
                    'block px-4 py-2 text-sm rounded-md transition-colors',
                    activeMenu === '/consumable-query'
                      ? 'bg-primary-600 text-white'
                      : 'text-gray-300 hover:bg-gray-700 hover:text-white'
                  ]"
                >
                  消耗查询
                </router-link>
                <router-link
                  v-if="hasAnyRole(['ADMIN', 'LEADER'])"
                  to="/consumable-statistics"
                  :class="[
                    'block px-4 py-2 text-sm rounded-md transition-colors',
                    activeMenu === '/consumable-statistics'
                      ? 'bg-primary-600 text-white'
                      : 'text-gray-300 hover:bg-gray-700 hover:text-white'
                  ]"
                >
                  易耗品统计
                </router-link>
              </div>
            </div>
          </li>
          
          <!-- 报表中心 -->
          <li v-if="hasAnyRole(['ADMIN', 'LEADER'])">
            <router-link
              to="/report"
              :class="[
                'flex items-center px-4 py-2 text-sm font-medium rounded-md mx-2 transition-colors',
                activeMenu === '/report'
                  ? 'bg-primary-600 text-white'
                  : 'text-gray-300 hover:bg-gray-700 hover:text-white'
              ]"
            >
              <DocumentTextIcon class="w-5 h-5 mr-3" />
              <span v-if="!isCollapse">报表中心</span>
            </router-link>
          </li>
          
          <!-- 用户管理 -->
          <li v-if="hasRole('ADMIN')">
            <div class="relative">
              <button
                @click="toggleSubMenu('user')"
                :class="[
                  'w-full flex items-center justify-between px-4 py-2 text-sm font-medium rounded-md mx-2 transition-colors',
                  'text-gray-300 hover:bg-gray-700 hover:text-white'
                ]"
              >
                <div class="flex items-center">
                  <UsersIcon class="w-5 h-5 mr-3" />
                  <span v-if="!isCollapse">用户管理</span>
                </div>
                <ChevronDownIcon 
                  v-if="!isCollapse"
                  :class="[
                    'w-4 h-4 transition-transform',
                    openSubMenus.user ? 'rotate-180' : ''
                  ]"
                />
              </button>
              
              <div v-if="!isCollapse && openSubMenus.user" class="ml-4 mt-1 space-y-1">
                <router-link
                  to="/user"
                  :class="[
                    'block px-4 py-2 text-sm rounded-md transition-colors',
                    activeMenu === '/user'
                      ? 'bg-primary-600 text-white'
                      : 'text-gray-300 hover:bg-gray-700 hover:text-white'
                  ]"
                >
                  用户列表
                </router-link>
                <router-link
                  to="/laboratory"
                  :class="[
                    'block px-4 py-2 text-sm rounded-md transition-colors',
                    activeMenu === '/laboratory'
                      ? 'bg-primary-600 text-white'
                      : 'text-gray-300 hover:bg-gray-700 hover:text-white'
                  ]"
                >
                  实验室管理
                </router-link>
              </div>
            </div>
          </li>
        </ul>
      </nav>
    </div>
    
    <!-- 主内容区 -->
    <div class="flex-1 flex flex-col overflow-hidden">
      <!-- 顶部栏 -->
      <header class="bg-white border-b border-gray-200 px-6 py-4">
        <div class="flex items-center justify-between">
          <div class="flex items-center space-x-4">
            <button
              @click="toggleCollapse"
              class="p-2 rounded-md text-gray-400 hover:text-gray-600 hover:bg-gray-100"
            >
              <Bars3Icon v-if="isCollapse" class="w-5 h-5" />
              <XMarkIcon v-else class="w-5 h-5" />
            </button>
            
            <!-- 面包屑导航 -->
            <nav class="flex" aria-label="Breadcrumb">
              <ol class="flex items-center space-x-2">
                <li v-for="(item, index) in breadcrumbs" :key="item.path" class="flex items-center">
                  <router-link
                    v-if="index < breadcrumbs.length - 1"
                    :to="item.path"
                    class="text-sm text-gray-500 hover:text-gray-700"
                  >
                    {{ item.title }}
                  </router-link>
                  <span v-else class="text-sm font-medium text-gray-900">
                    {{ item.title }}
                  </span>
                  <ChevronRightIcon
                    v-if="index < breadcrumbs.length - 1"
                    class="w-4 h-4 text-gray-400 mx-2"
                  />
                </li>
              </ol>
            </nav>
          </div>
          
          <!-- 用户信息 -->
          <div class="relative">
            <button
              @click="showUserMenu = !showUserMenu"
              class="flex items-center space-x-2 text-sm text-gray-700 hover:text-gray-900"
            >
              <UserCircleIcon class="w-8 h-8" />
              <span>{{ userInfo.realName }}</span>
              <ChevronDownIcon class="w-4 h-4" />
            </button>
            
            <!-- 用户下拉菜单 -->
            <div
              v-if="showUserMenu"
              class="absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 z-50 border border-gray-200"
            >
              <button
                @click="handleCommand('profile')"
                class="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
              >
                个人信息
              </button>
              <hr class="my-1">
              <button
                @click="handleCommand('logout')"
                class="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
              >
                退出登录
              </button>
            </div>
          </div>
        </div>
      </header>
      
      <!-- 内容区 -->
      <main class="flex-1 overflow-auto bg-gray-50">
        <router-view />
      </main>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  HomeIcon,
  ComputerDesktopIcon,
  ChartBarIcon,
  ArchiveBoxIcon,
  DocumentTextIcon,
  UsersIcon,
  ChevronDownIcon,
  ChevronRightIcon,
  Bars3Icon,
  XMarkIcon,
  UserCircleIcon
} from '@heroicons/vue/24/outline'
import { useUserStore } from '@/stores/user'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const isCollapse = ref(false)
const showUserMenu = ref(false)
const openSubMenus = ref({
  equipment: false,
  statistics: false,
  consumable: false,
  user: false
})

// 计算属性
const userInfo = computed(() => userStore.userInfo)
const userRole = computed(() => userStore.userRole)

// 当前激活的菜单
const activeMenu = computed(() => route.path)

// 面包屑导航
const breadcrumbs = computed(() => {
  const matched = route.matched.filter(item => item.meta && item.meta.title)
  return matched.map(item => ({
    title: item.meta.title,
    path: item.path
  }))
})

// 权限检查方法
const hasRole = (role) => userStore.hasRole(role)
const hasAnyRole = (roles) => userStore.hasAnyRole(roles)

// 切换侧边栏折叠状态
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
  // 折叠时关闭所有子菜单
  if (isCollapse.value) {
    openSubMenus.value = {
      equipment: false,
      statistics: false,
      consumable: false,
      user: false
    }
  }
}

// 切换子菜单
const toggleSubMenu = (menu) => {
  if (isCollapse.value) return
  openSubMenus.value[menu] = !openSubMenus.value[menu]
}

// 处理用户菜单命令
const handleCommand = async (command) => {
  showUserMenu.value = false
  
  switch (command) {
    case 'profile':
      alert('个人信息功能待开发')
      break
    case 'logout':
      if (confirm('确定要退出登录吗？')) {
        userStore.logout()
        router.push('/login')
      }
      break
  }
}

// 点击外部关闭用户菜单
const handleClickOutside = (event) => {
  if (!event.target.closest('.relative')) {
    showUserMenu.value = false
  }
}

// 监听路由变化，自动关闭用户菜单并展开相应的子菜单
watch(route, () => {
  showUserMenu.value = false
  
  // 根据当前路由自动展开相应的子菜单
  const path = route.path
  if (path.startsWith('/equipment') || path.startsWith('/equipment-application') || path.startsWith('/equipment-borrow')) {
    openSubMenus.value.equipment = true
  } else if (path.startsWith('/equipment-statistics') || path.startsWith('/equipment-repair') || path.startsWith('/equipment-scrap')) {
    openSubMenus.value.statistics = true
  } else if (path.startsWith('/consumable-plan') || path.startsWith('/consumable-receive') || path.startsWith('/consumable-query') || path.startsWith('/consumable-statistics')) {
    openSubMenus.value.consumable = true
  } else if (path.startsWith('/user') || path.startsWith('/laboratory')) {
    openSubMenus.value.user = true
  }
}, { immediate: true })

// 添加全局点击事件监听
document.addEventListener('click', handleClickOutside)
</script>